import { DataEventType } from '@app-nextmesh-env/nextmesh/types'
import { events } from '@app-nextmesh-env/nextmesh/utils'
import Paper from '@mui/material/Paper'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableContainer from '@mui/material/TableContainer'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'
import { styled } from '@mui/material/styles'
import { useEffect, useState } from 'react'


const StyledTableRow = styled(TableRow)(({ theme }) => ({
  '&:nth-of-type(odd)': {
    backgroundColor: theme.palette.action.hover,
  },
  // hide last border
  '&:last-child td, &:last-child th': {
    border: 0,
  },
}))

export default function TableView() {
  const [header, setHeader] = useState<string[]>([])
  const [rows, setRows] = useState<any[][]>([[]])

  useEffect(() => {
    events.on(DataEventType.UpdateTable, (tableHeader, tableBody) => {
      setHeader(tableHeader)
      setRows(tableBody)
    })

    return () => {
      events.off(DataEventType.UpdateTable)
    }
  })
  return (
    <Paper sx={{ width: '100%', overflow: 'hidden' }}>
      <TableContainer sx={{ width: 'max-content', maxHeight: '240px' }}>
        <Table stickyHeader
          aria-label="sticky table"
          size={'small'}>
          <TableHead>
            <TableRow>
              {header.map((headCell, index) => (
                <TableCell key={index} width={'10px'}>
                  {headCell}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.map((row, index) => {
              return (
                <StyledTableRow
                  hover
                  role="checkbox"
                  tabIndex={-1}
                  key={index}
                  sx={{ cursor: 'pointer' }}>
                  {row.map((cell, index) => (
                    <TableCell key={index} width={'10px'}>
                      {cell}
                    </TableCell>
                  ))}
                </StyledTableRow>
              )
            })}
          </TableBody>
        </Table>
      </TableContainer>
    </Paper>
  )
}
